package com.org.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.org.pojo.Serve;
import com.org.pojo.Skill;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.system.ApplicationPid;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 用高德地图的api来计算两点之间的距离
 */
public class MapUtil {

    private static final String key = "4a36e7c9e0cc5c537de4efb4d3b671ab";

    private static final String api = "https://restapi.amap.com/v3/distance";

    // 定位
//    public static String getLocation(){
//        Geolocation geolocation = GeolocationAPI.getCurrentPosition();
//
//    }

    // 返回两点之间的距离
    public static int getDistance(String origins, String destination) {

        // 这是用高德api来获取距离
//        String url = api + "?Key=" + key + "&origins=" + origins + "&destination=" + destination + "&type=0";
//        double distance = 0;
//
//        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//            // 创建HTTP GET请求
//            HttpGet httpGet = new HttpGet(url);
//            // 执行请求并获取响应
//            try(CloseableHttpResponse response = httpClient.execute(httpGet)){
//                // 解析服务器的响应数据
//                String responseBody = EntityUtils.toString(response.getEntity());
//                // 将返回结果转为 json
//                Gson gson = new GsonBuilder().setPrettyPrinting().create();
//                JsonObject json = gson.fromJson(responseBody, JsonObject.class);
//                if (!json.get("status").getAsString().equals("1")) {
//                    throw new Exception("获取距离信息失败");
//                }
//                distance = json.get("results").getAsJsonArray().get(0).getAsJsonObject().get("distance").getAsDouble();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return (int)distance;

        // 这是直接计算(这里假设地球是个完美的球体，结果可能不准)
        double lat1 = Double.parseDouble(origins.split(",")[0]);
        double lon1 = Double.parseDouble(origins.split(",")[1]);
        double lat2 = Double.parseDouble(destination.split(",")[0]);
        double lon2 = Double.parseDouble(destination.split(",")[1]);
        int r = 6371000; // meters
        double phi1 = Math.toRadians(lat1);
        double phi2 = Math.toRadians(lat2);
        double deltaPhi = Math.toRadians(lat2 - lat1);
        double deltaLambda = Math.toRadians(lon2 - lon1);

        double a = Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +
                Math.cos(phi1) * Math.cos(phi2) *
                        Math.sin(deltaLambda / 2) * Math.sin(deltaLambda / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return (int)(r * c);
    }

    // 高并发获取距离
    public static List<Skill> setSkillDistances(List<Skill> skills, String location){
        // 更新每个skill的distance
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (Skill skill : skills) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                String skillLocation = skill.getLocation();
                double distance = getDistance(location, skillLocation);
                skill.setDistance(distance);
            });
            futures.add(future);
        }
        // 等待所有的异步任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        return skills;
    }

    // 高并发获取距离
    public static List<Serve> setServeDistances(List<Serve> serves, String location){
        // 更新每个skill的distance
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (Serve serve : serves) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                String serveLocation = serve.getLocation();
                double distance = getDistance(location, serveLocation);
                serve.setDistance(distance);
            });
            futures.add(future);
        }
        // 等待所有的异步任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        return serves;
    }


}
